import Vue from 'vue'
import VueRouter from 'vue-router'
import store from './../store/index'
import { storage } from './../assets/js/util'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import Home from '../views/Home.vue' // 同步
// 懒加载
// const Login = () => import('../views/Login')
// const Loading = () => import('../views/Loading.vue')

Vue.use(VueRouter)

NProgress.configure({ showSpinner: true })
const routes = [
    {
        path: '/',
        name: 'Home',
        component: Home,
        meta: {
            title: '列表'
        }
    },
    {
        path: '/rowspan',
        name: 'Rowspan',
        component: () => import('@/views/Rowspan'),
        meta: {
            title: '行合并demo'
        }
    }
]

const router = new VueRouter({
    routes
})

router.beforeEach((to, from, next) => {
    NProgress.start()
    /* 路由发生变化修改页面title */
    if (to.meta.title) {
        document.title = to.meta.title
    }
    if (to.meta.auth) {
        let token = store.state.user.token
        console.log('路由token', token)
        if (!token) {
            const storageToke = storage.get('token')
            if (storageToke) {
                token = storageToke
                store.commit('user/setToken', storageToke)
            }
        }
        if (store.state.user.token) { // 判断是否有token
            next() // 已登录
        } else {
            next({
                path: '/login',
                query: { redirect: to.fullPath } // 将跳转的路由path作为参数，登录成功后跳转到该路由
            })
        }
    } else {
        next()
        console.log('无需登陆')
    }
})
router.afterEach(() => {
    NProgress.done()
})

export default router
